package com.stone.serverless.mybatis;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.stone.serverless.sdk.event.ComponentRefresh;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/17 15:52
 * @Version: 1.0.0
 */
public class DbOutServiceRefreshManager implements ComponentRefresh {


    @Override
    public void refresh() {
        SqlSessionFactoryBean bean = SpringUtil.getBean(SqlSessionFactoryBean.class);
        bean.setDataSource(NeedOutServiceManager.INSTANCE.dataSourceService.dataSource());
        SqlSessionFactory object = null;
        try {
            object = bean.getObject();
            Configuration configuration = object.getConfiguration();
            Environment environment = configuration.getEnvironment();
            ReflectUtil.setFieldValue(environment, "dataSource", NeedOutServiceManager.INSTANCE.dataSourceService.dataSource());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //  SpringManagedTransactionFactory bean1 = SpringUtil.getBean(SpringManagedTransactionFactory.class);
        //    bean1.setDataSource(NeedOutServiceManager.INSTANCE.dataSourceService.dataSource());
    }
}
